package com.panda.order.taobao;

import com.alibaba.fastjson.JSON;
import com.panda.order.domain.TPandaOrderBuyer;
import com.panda.order.domain.TPandaOrderHead;
import com.panda.system.common.constant.EnumConstants;
import com.panda.system.common.constant.RedisKeyConstants;
import com.panda.system.domain.PandaStore;
import com.panda.system.service.IPandaStoreService;
import com.panda.system.service.ISysConfigService;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Trade;
import com.taobao.api.request.TradesSoldIncrementGetRequest;
import com.taobao.api.response.TradesSoldIncrementGetResponse;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 同步订单API
 */
@Service
public class TbGetOrderListApi {
    private static final Logger log = LoggerFactory.getLogger(TbGetOrderListApi.class);
    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private  IPandaStoreService storeService;

    // 淘宝订单字段
    private static String fields = "tid,pic_path,payment,seller_rate,post_fee,consign_time,received_payment,order_tax_fee," +
            "num_iid,type,price,discount_fee,total_fee,created,pay_time,modified,end_time,seller_flag,buyer_nick," +
            "has_buyer_message,mark_desc,shipping_type,adjust_fee,trade_from,buyer_rate,delivery_time,collect_time," +
            "dispatch_time,sign_time,delivery_cps,receiver_name,receiver_state,receiver_address,receiver_zip," +
            "receiver_mobile,receiver_phone,receiver_country,receiver_town,receiver_city,receiver_district,orders,status";
    private static String status = "fixed,auction,guarantee_trade,step,independent_simple_trade,independent_shop_trade,auto_delivery,ec,cod,game_equipment,shopex_trade,netcn_trade,external_trade,instant_trade,b2c_cod,hotel_trade,super_market_trade,super_market_cod_trade,taohua,waimai,o2o_offlinetrade,nopaid,step,eticket,tmall_i18n,nopaid,insurance_plus,finance,pre_auth_type,lazada";

    public List<TPandaOrderHead> doGetTbOrder(Date lastRun){
        log.info("淘宝订单同步，最后执行时间：{}",lastRun);
        List<TPandaOrderHead> orderHeads = new ArrayList<>();
        String serverUrl = sysConfigService.selectConfigByKey(RedisKeyConstants.TAOBAO_URL);
        String appKey = sysConfigService.selectConfigByKey(RedisKeyConstants.TAOBAO_APPKEY); // 可替换为您的应用的AppKey
        String appSecret = sysConfigService.selectConfigByKey(RedisKeyConstants.TAOBAO_APPSECRET); // 可替换为您的应用的AppSecret
        PandaStore pandaStore = new PandaStore();
        pandaStore.setStatus(EnumConstants.SysStatus.OPEN.getCode());
        List<PandaStore> pandaStores = storeService.selectPandaStoreList(pandaStore);
        // 初始化客户端
        TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        // 设置请求参数
        TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest ();
        req.setFields(fields);
        req.setPageSize(100L);
        req.setStatus(status);
        req.setUseHasNext(true);
        if(lastRun!=null){
            Calendar beforeTime = Calendar.getInstance();
            beforeTime.setTime(lastRun);
            beforeTime.add(Calendar.MINUTE, -15);
            req.setStartModified(beforeTime.getTime());
            req.setEndModified(new Date());
        }

        for(PandaStore store:pandaStores){
            req.setPageNo(1L);
            String sessionKey = store.getSecret();
            if(Strings.isNotEmpty(sessionKey)&&store.getFailureTime()!=null&&new Date().before(store.getFailureTime())){
                log.info("同步淘宝订单，开始。店铺：{}",store.getStoreName());
                log.info("同步淘宝订单入参：{}",JSON.toJSONString(req));
                List<TPandaOrderHead> storeOrders = getStoreOrder(client, sessionKey,req,store.getStoreId());
                orderHeads.addAll(storeOrders);
            }
        }
        log.info("淘宝订单信息：{}",JSON.toJSONString(orderHeads));
        return orderHeads;
    }

    private List<TPandaOrderHead> getStoreOrder(TaobaoClient client,String sessionKey,TradesSoldIncrementGetRequest req,Long storeId){
        List<TPandaOrderHead> storeOrders =new ArrayList<>();
        try {
            TradesSoldIncrementGetResponse rsp = client.execute(req, sessionKey);
            // 解析转换返回值
            List<TPandaOrderHead> orderHeads = processOrderList(rsp,storeId);
            storeOrders.addAll(orderHeads);
            if(rsp.getHasNext()){
                req.setPageNo(req.getPageNo()+1);
                List<TPandaOrderHead> storeOrder = getStoreOrder(client, sessionKey, req,storeId);
                storeOrders.addAll(storeOrder);
            }
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return storeOrders;
    }

    private List<TPandaOrderHead> processOrderList(TradesSoldIncrementGetResponse rsp ,Long storeId){
        List<TPandaOrderHead> storeOrders =new ArrayList<>();
        List<Trade> trades = rsp.getTrades();
        if(!CollectionUtils.isEmpty(trades)){
            for(Trade trade:trades){
                // 设置head
                String tradesStr = JSON.toJSONString(trade);
                TPandaOrderHead tPandaOrderHead = JSON.parseObject(tradesStr, TPandaOrderHead.class);
                tPandaOrderHead.setStoreId(String.valueOf(storeId));
                // 设置买家信息
                TPandaOrderBuyer orderBuyer = JSON.parseObject(tradesStr, TPandaOrderBuyer.class);
                tPandaOrderHead.setOrderBuyer(orderBuyer);
                storeOrders.add(tPandaOrderHead);
            }
        }

        return storeOrders;
    }

}
